﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dukou.Security;
using System.Threading;
using System.Web;
using System.Web.Security;

namespace Dukou.Web
{
    public class WebCurrentUserContext : ICurrentUserContext
    {
        /// <summary>
        /// 用户会话ID
        /// </summary>
        private static string DUKOU_USER_SESSIONID = "DUKOU_USER_SESSIONID";

        /// <summary>
        /// 用户IP地址
        /// </summary>
        private static string DUKOU_USER_IP = "DUKOU_USER_IP";

        /// <summary>
        /// 用户数据
        /// </summary>
        private static string DUKOU_USER_DATA = "DUKOU_USER_DATA";

        public string SessionID
        {
            get { return Thread.GetData(Thread.GetNamedDataSlot(DUKOU_USER_SESSIONID)) as string; }
        }

        public string IP
        {
            get { return Thread.GetData(Thread.GetNamedDataSlot(DUKOU_USER_IP)) as string; }
        }

        public string UserData
        {
            get { return Thread.GetData(Thread.GetNamedDataSlot(DUKOU_USER_DATA)) as string; }
        }

        public void Init()
        {
            HttpContext context = HttpContext.Current;
            string userData = null;
            HttpCookie cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (cookie != null && !string.IsNullOrEmpty(cookie.Value))
            {
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
                if (ticket != null)
                {
                    userData = ticket.UserData;
                }
            }

            string sessionId = context.Session.SessionID;
            string ip = context.Request.UserHostAddress;
            this.SetData(sessionId, ip, userData);
        }

        private void SetData(string sessionId, string ip, string userData)
        {
            Thread.SetData(Thread.GetNamedDataSlot(DUKOU_USER_SESSIONID), sessionId);
            Thread.SetData(Thread.GetNamedDataSlot(DUKOU_USER_IP), ip);
            Thread.SetData(Thread.GetNamedDataSlot(DUKOU_USER_DATA), userData);
        }
    }
}
